<?php

namespace common\models;

use yii\db\ActiveRecord;

class User extends ActiveRecord{
    
    const SUPER_ID = 9;


    public static function tableName(){
        return '{{%user}}';
    }
    
    public function rules() {
       
        return [
            ['username', 'checkName', 'skipOnEmpty' => false],
            ['password', 'string', 
                'min' => 6, 
                'tooShort' => '太短了', 
                'skipOnEmpty' => false,
                'when'=>function($model){
                    return ($model->isNewRecord || $model->password != null);
                }
            ],
            ['status', 'in', 'range' => [0, 1], 'message' => '非法操作']
        ];
    }
    
    public function checkName($attribute,$params){
        if(!preg_match("/^[\w]{2,30}$/",$this->$attribute)){
            $this->addError($attribute,'Error!!!');
        }else if(self::find()->where([
            'username'=>$this->$attribute])
            ->andWhere(['!=','id',$this->id])   
            ->count()>0){
             echo '该用户名已存在!!!';
        }
    }
    
    public function beforeSave($insert) {
        if(parent::beforeSave($insert)){
            if($this->isNewRecord){
                $this->date= $this->login_date=time();
            }
            if(empty($this->password)){
                unset($this->password);
            }else{
                $this->password = md5($this->password);
            }
            
            return true;
        }
        return false;
    }
    
    public static function deleteIn($selected){
        
        $data=[];
        foreach ($selected as $v){
            if($v == self::SUPER_ID) { continue;}
            $data[] = (int)$v;
        }
        return self::deleteAll(['id'=>$data]);
    }
}